package com.caiden_micheal.dynamic.form_change.service.impl;

import com.caiden_micheal.base.domain.AjxResult;
import com.caiden_micheal.dynamic.form_change.dto.FormChangePersonDataRecordDTO;
import com.caiden_micheal.dynamic.form_change.mapper.FormChangePersonDataMapper;
import com.caiden_micheal.dynamic.form_change.service.FormChangePersonDataService;
import com.caiden_micheal.dynamic.form_change.vo.FormChangePersonDataRecordVO;
import com.caiden_micheal.user.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FormChangePersonDataServiceImpl implements FormChangePersonDataService {
    private static final Logger logger = LoggerFactory.getLogger(FormChangePersonDataServiceImpl.class);


    @Autowired
    private FormChangePersonDataMapper formChangePersonDataMapper;
    @Autowired
    private UserMapper userMapper;

    @Transactional
    @Override
    public AjxResult findFormChangePersonDataRecord(FormChangePersonDataRecordDTO formChangePersonDataRecordDTO) {
        if (formChangePersonDataRecordDTO == null || formChangePersonDataRecordDTO.getFormChangeId() == null) {
            return AjxResult.paramError("参数传递有误");
        }
        try {
            List<FormChangePersonDataRecordVO> formChangePersonDataRecordVOList = formChangePersonDataMapper.findVOResultByFormChangeId(formChangePersonDataRecordDTO.getFormChangeId());
            if (formChangePersonDataRecordVOList == null || formChangePersonDataRecordVOList.size() == 0) {
                return AjxResult.processError("表单变动流程未启动或遭人工删除");
            }
            List<String> usernameList = formChangePersonDataRecordVOList.stream().map(FormChangePersonDataRecordVO::getProcessorUsername).collect(Collectors.toList());
            Map<String, Map<String, String>> userResultMap = userMapper.findMapByUsernameList(usernameList);
            for (FormChangePersonDataRecordVO formChangePersonDataRecordVO : formChangePersonDataRecordVOList) {
                Map<String, String> userTempMap = userResultMap.get(formChangePersonDataRecordVO.getProcessorUsername());
                if (userTempMap != null) {
                    formChangePersonDataRecordVO.setProcessorName(userTempMap.get("name"));
                    formChangePersonDataRecordVO.setProcessorOrgName(userTempMap.get("org_name"));
                }
            }
            return AjxResult.success(formChangePersonDataRecordVOList);
        } catch (Exception e) {
            logger.error(e.toString());
            return AjxResult.unknownError("数据库操作异常");
        }
    }
}
